package com.situ.crm.test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.junit.Test;

public class ThreadPoolDemo {

	public static void main(String[] args) {
		// 创建线程池对象,包含2个线程对象
		ExecutorService executorService = Executors.newFixedThreadPool(2);
		ThreadPoolRunnable runnable = new ThreadPoolRunnable();

		// 不使用线程池启动线程的方式
		// Thread thread = new Thread(runnable);
		// thread.start();
		// 从线程池中获取线程对象,然后调用MyRunnable中的run()
		executorService.submit(runnable);
		executorService.submit(runnable);
		executorService.submit(runnable);
		// 注意：submit方法调用结束后，程序并不终止，是因为线程池控制了线程的关闭。将使用完的线程又归还到了线程池中

		// 关闭线程池，一般不使用，因为我们使用线程池的目的就是为了复用线程。
		executorService.shutdown();
	}

	@Test
	public void test() throws InterruptedException, ExecutionException {
		// 创建线程池对象,包含2个线程对象
		ExecutorService executorService = Executors.newFixedThreadPool(2);
		ThreadPoolCallable callable = new ThreadPoolCallable();
		// 从线程池中获取线程对象
		Future<String> submit = executorService.submit(callable);
		String result = submit.get();
		System.out.println("线程名字： " + result);

		// 关闭线程池，一般不使用，因为我们使用线程池的目的就是为了复用线程。
		executorService.shutdown();
	}

	@Test
	public void test2() throws InterruptedException, ExecutionException {
		ExecutorService executorService = Executors.newFixedThreadPool(2);
		Future future1 = executorService.submit(new CalculateCallable(1, 100));
		System.out.println(future1.get());
		Future future2 = executorService.submit(new CalculateCallable(1, 10));
		System.out.println(future2.get());
		Future future3 = executorService.submit(new CalculateCallable(1, 20));
		System.out.println(future3.get());
	}
}
